<template>
  <ToolBar @onClick="handlerOk" :menus="menus" />
  <div class="flex" v-loading="loading">
    <el-input
      type="textarea"
      rows="15"
      placeholder="输入你的想法，帮你生成回复内容。"
      v-model="content" 
      resize="none"
      ref="inputRef"
    />
  </div>
</template>
  
<script lang="ts" setup>
  import { defineProps, ref, defineAsyncComponent, onMounted } from 'vue';
  import api from "/@/api/email/index"
  import { ElMessage } from 'element-plus';

  const inputRef = ref();

  const ToolBar = defineAsyncComponent(() => import('/@/components/ToolBar/index.vue'));
  const menus = [
    {
      label: '确认',
      id: 'ok',
    }
  ];

  const props = defineProps({
    emailId: {
      type: String,
      default: '',
    },
  });

  const emit = defineEmits(['success']);
  const content = ref('');
  const loading = ref(false);

  const handlerOk = async () => {
    if (!content.value) {
      ElMessage.warning('请输入内容');
      return;
    }

    if (loading.value) {
      return;
    }

    loading.value = true;
    let res;
    try {
      if (props.emailId) {
        res = await api.email.emailWrite({
          id: props.emailId,
          input: content.value
        });
      } else {
        res = await api.email.expression(content.value);
        if (res.data.code === false) {
          loading.value = false;
          ElMessage.warning(res.data.msg);
          return;
        }
      } 
    } catch (error) {
      loading.value = false;
      return;
    }
    
    content.value = "";
    emit('success',  res.data);
    loading.value = false;
  };

  onMounted(() => {
    if (inputRef.value && inputRef.value.focus) {
      inputRef.value.focus();
    }
  });
</script>
<style lang="scss" scoped>
</style>  